import { Modal, ModalProps, Input, Button, Upload, UploadFile, message } from 'antd';
import '../styles/entry.scss';
import { useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import knowService from '@/api/services/knowService';
import { AxiosProgressEvent } from 'axios';

interface Props extends ModalProps {
  onConfirm?: (
    data: FormData,
    onUploadProgress: (event: AxiosProgressEvent) => void,
  ) => Promise<void>;
  templateUrl?: string;
}

const ImportModal = ({ open, templateUrl, onConfirm, onCancel, title, ...props }: Props) => {
  const [fileList, setFileList] = useState<File[]>([]);
  const [uploading, setUploading] = useState(false);

  const onUploadProgress = (event: AxiosProgressEvent) => {
    console.log('Upload progress:', event.progress);
  };

  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.error('请先上传文件！');
      return;
    }
    setUploading(true);
    try {
      const uploadFile = fileList[0];
      const formData = new FormData();
      formData.append('file', uploadFile, encodeURIComponent(uploadFile.name));
      onConfirm && (await onConfirm(formData, onUploadProgress));
      setFileList([]);
    } catch (error) {
      message.error('上传失败！');
    } finally {
      setUploading(false);
    }
  };

  const beforeUpload = (file: File) => {
    setFileList((prevList) => [...prevList, file]);
    return false; // 阻止自动上传
  };

  return (
    <Modal
      destroyOnClose={true}
      maskClosable={false}
      onCancel={onCancel}
      open={open}
      {...props}
      footer={null}
    >
      <div className="m-2 text-center text-lg font-bold">{title}</div>
      <div className="mb-2">
        <p>
          1.根据词条模板整理要导入的词条。
          <a href={templateUrl}>
            <span className="text-@brand-color underline">下载词条模板</span>
          </a>
        </p>
        <p>2.整理好词条后，点击文件上传，整理好的文件。</p>
        <p>3.上传文件完成后点击确认导入。</p>
      </div>
      <div className="mt-2 flex flex-col">
        <Upload
          accept=".xls,.xlsx"
          fileList={fileList}
          beforeUpload={beforeUpload}
          onRemove={(file) => {
            setFileList((prevList) => prevList.filter((item) => item.uid !== file.uid));
          }}
        >
          <Button loading={uploading} icon={<UploadOutlined />}>
            上传文件
          </Button>
        </Upload>
      </div>
      <div className="mt-4 flex items-center justify-center gap-10">
        <Button onClick={onCancel}>取消</Button>
        <Button loading={uploading} type="primary" onClick={handleUpload}>
          确认导入
        </Button>
      </div>
    </Modal>
  );
};

export default ImportModal;
